import axios from "axios";
import querystring from "querystring";
import errorCode from "./errorCode";
import { Message } from "element-ui";
import { filterObject } from "@/utils/filter.js";
import router from "@/permission.js";
import { getToken, removeToken } from "@/utils/auth";


const service = axios.create({
    timeout: 30000,
    withCredentials: true,
    baseURL: process.env.VUE_APP_URL,
    validateStatus: function (status) {
        return status >= 200 && status <= 500; // 默认的
    },
});

// request拦截器
service.interceptors.request.use(
    config => {
        // 判断是否需要token
        const token = getToken()
        if (!config.noToken) {
            config.headers.Authorization = `bearer ${token}`
        }
        // post请求
        if (
            config.method === "post" &&
            config.headers["content-type"] === "application/x-www-form-urlencoded"
        ) {
            let d = filterObject(config.data);
            config.data = querystring.stringify(d);
        }
        // get请求
        if (config.method === "get") {
            config.params = filterObject(config.params);

        }
        return config;
    },
    (error) => {
        return Promise.reject(new Error(error));
    }
);

// response拦截器
service.interceptors.response.use(
    res => {
        const status = Number(res.status) || 200;
        const message = res.data.msg || errorCode[status] || errorCode["default"];
        let data = new Object();
        if (status === 401) {
            // 登出
            removeToken();
            router.push({
                path: "/login"
            });
            return;
        } else if (
            status === 200
        ) {
            data = res.data;
        } else {
            Message({
                message: message,
                type: "error",
            });
            return Promise.reject(new Error(message));
        }
        return data;
    },
    error => {
        return Promise.reject(error);
    }
);

export default service;
